package com.jintian.smart.kernel.switching.fn;

import com.jintian.smart.kernel.core.annotation.beetl.BeetlFunction;
import org.beetl.core.Context;
import org.beetl.core.Function;
import org.beetl.sql.core.ExecuteContext;
import org.beetl.sql.core.db.DBType;

@BeetlFunction(code = "dbRow2Json")
public class DbRow2Json implements Function {

	@Override
	public Object call(Object[] paras, Context ctx) {
		String prefix = paras[0].toString();
		String[] recordAttrs = paras[1].toString().split(",");
		ExecuteContext context = (ExecuteContext) ctx.getGlobal(ExecuteContext.NAME);
		if (DBType.DB_MYSQL == context.sqlManager.getDbStyle().getDBType()) {

			return mysqlJson(prefix, recordAttrs);
		} else if (DBType.DB_ORACLE == context.sqlManager.getDbStyle().getDBType()) {
			return oracleJson(prefix, recordAttrs);
		}
		return null;
	}

	private String mysqlJson(String prefix, String[] recordAttrs) {
		// concat('{'
		// ,'"attr":"',old.attr,'"'
		// ,'}')
		StringBuffer ret = new StringBuffer("concat('{'");
		int idx = 0;
		for (String attr : recordAttrs) {
			ret.append(idx++ == 0 ? "" : ",','")
					//
					.append(",'\"").append(attr).append("\":\"',").append(prefix).append(".").append(attr)
					.append(",'\"'");
		}
		ret.append(",'}')");
		return ret.toString();
	}

	private String oracleJson(String prefix, String[] recordAttrs) {
		// '{'
		// || '"' || 'attr' || '":"' || :old.attr || '"'
		// || '}'
		StringBuffer ret = new StringBuffer("'{'");
		int idx = 0;
		for (String attr : recordAttrs) {
			ret.append(idx++ == 0 ? "" : " || ',' ").append(" || '\"' || '").append(attr).append("' || '\":\"' || ")
					.append(prefix).append(".").append(attr).append(" || '\"'");
		}
		ret.append(" || '}'");
		return ret.toString();
	}

	public static void main(String[] args) {
		System.out.println("select " + new DbRow2Json().mysqlJson("old", new String[] { "id", "c1", "c3" })
				+ " form my_test1 as old");
		System.out.println("select " + new DbRow2Json().oracleJson("old", new String[] { "fbizrecid" })
				+ " from na_zjrk_sjqd as old");
	}
}
